package org.springframework.security.web.util.matcher;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UrlPathHelper;

import java.util.Collections;
import java.util.Map;

/**
 * @author Dillon
 * @date 2024/7/2
 * @slogan 致敬大师 致敬未来的你
 * @desc 请求匹配器实现类，用于通过URL风格来匹配请求
 */
public final class AntPathRequestMatcher implements RequestMatcher, RequestVariablesExtractor {

	/**
	 * 全路径匹配表达式
	 */
	private static final String MATCH_ALL = "/**";

	private final Matcher matcher;

	/**
	 * 待匹配路径表达式
	 */
	private final String pattern;

	/**
	 * 待匹配方法
	 */
	private final HttpMethod httpMethod;

	private final boolean caseSensitive;

	private final UrlPathHelper urlPathHelper;

	/**
	 * 静态工厂方法，获取 AntPathRequestMatcher 对象
	 *
	 * @param pattern 待匹配路径表达式
	 * @return AntPathRequestMatcher 对象
	 */
	public static AntPathRequestMatcher antMatcher(String pattern) {
		Assert.hasText(pattern, "表达式不能为空");
		return new AntPathRequestMatcher(pattern);
	}

	/**
	 * 静态工厂方法，获取 AntPathRequestMatcher 对象
	 *
	 * @param method 请求方法
	 * @return AntPathRequestMatcher 对象
	 */
	public static AntPathRequestMatcher antMatcher(HttpMethod method) {
		Assert.notNull(method, "方法不能为空");
		return new AntPathRequestMatcher(MATCH_ALL, method.name());
	}

	/**
	 * 静态工厂方法，获取 AntPathRequestMatcher 对象
	 *
	 * @param method  请求方法
	 * @param pattern 待匹配路径表达式
	 * @return AntPathRequestMatcher 对象
	 */
	public static AntPathRequestMatcher antMatcher(HttpMethod method, String pattern) {
		Assert.hasText(pattern, "表达式不能为空");
		Assert.notNull(method, "方法不能为空");
		return new AntPathRequestMatcher(pattern, method.name());
	}

	/**
	 * 构造函数
	 *
	 * @param pattern 待匹配请求路径
	 */
	public AntPathRequestMatcher(String pattern) {
		this(pattern, null);
	}

	/**
	 * 构造函数
	 *
	 * @param pattern    待匹配请求路径
	 * @param httpMethod 待匹配请求方法
	 */
	public AntPathRequestMatcher(String pattern, String httpMethod) {
		this(pattern, httpMethod, true);
	}

	/**
	 * 构造函数
	 *
	 * @param pattern       待匹配请求路径
	 * @param httpMethod    待匹配请求方法
	 * @param caseSensitive 是否区分大小写
	 */
	public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive) {
		this(pattern, httpMethod, caseSensitive, null);
	}

	/**
	 * 构造函数
	 *
	 * @param pattern       待匹配请求路径
	 * @param httpMethod    待匹配请求方法
	 * @param caseSensitive 是否区分大小写
	 * @param urlPathHelper URL路径辅助类
	 */
	public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive, UrlPathHelper urlPathHelper) {
		Assert.hasText(pattern, "表达式不能为空");
		this.caseSensitive = caseSensitive;
		// 全路径匹配URL赋值 如果是全路径，则不需要matcher
		if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
			pattern = MATCH_ALL;
			this.matcher = null;
		} else {
			// 根据路径匹表达式不同使用不同的匹配器实现
			// 如果是 /** 结尾 且没有 {}?* 等特殊符号， 使用 SubpathMatcher 匹配器
			// 否则使用 SpringAntMatcher 匹配器
			if (pattern.endsWith(MATCH_ALL) && (pattern.indexOf('?') == -1 && pattern.indexOf('{') == -1 && pattern.indexOf('}') == -1)
					&& pattern.indexOf("*") == pattern.length() - 2) {
				this.matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3), caseSensitive);
			} else {
				this.matcher = new SpringAntMatcher(pattern, caseSensitive);
			}
		}
		this.pattern = pattern;
		this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
		this.urlPathHelper = urlPathHelper;
	}

	/**
	 * 传入请求，用于判断是否匹配某种条件
	 *
	 * @param request 请求对象
	 * @return 是否匹配条件
	 */
	@Override
	public boolean matches(HttpServletRequest request) {
		// 请求方式比较
		if (this.httpMethod != null && StringUtils.hasText(request.getMethod()) && this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
			return false;
		}
		// 如果全路径，直接返回真
		if (this.pattern.equals(MATCH_ALL)) {
			return true;
		}
		// 获取请求路径并通过匹配器匹配，两个子类
		String url = getRequestPath(request);
		return this.matcher.matches(url);
	}

	@Override
	@Deprecated
	public Map<String, String> extractUriTemplateVariables(HttpServletRequest request) {
		return matcher(request).getVariables();
	}

	/**
	 * 传入请求，获取请求参数结果
	 *
	 * @param request 请求对象
	 * @return 参数结果
	 */
	@Override
	public MatchResult matcher(HttpServletRequest request) {
		// 如果不匹配，返回空结果，标记为不匹配
		if (!matches(request)) {
			return MatchResult.notMatch();
		}
		// 如果匹配器为空，返回空结果 标记为匹配
		if (this.matcher == null) {
			return MatchResult.match();
		}
		// 从请求结果中获取URL
		String url = getRequestPath(request);
		// 通过matcher 获取路径中参数
		return MatchResult.match(this.matcher.extractUriTemplateVariables(url));
	}

	/**
	 * 从请求对象中获取请求路径
	 *
	 * @param request 请求对象
	 * @return 请求全路径
	 */
	private String getRequestPath(HttpServletRequest request) {
		// 如果路径匹配辅助类不为空，则优先使用  urlPathHelper
		if (this.urlPathHelper != null) {
			return this.urlPathHelper.getPathWithinApplication(request);
		}
		// 获取请求二级以及后面域名
		String url = request.getServletPath();
		// 获取二级域名*解析到的真实域名
		String pathInfo = request.getPathInfo();
		// 拼接域名并返回
		if (pathInfo != null) {
			url = StringUtils.hasLength(url) ? url + pathInfo : pathInfo;
		}
		return url;
	}

	/**
	 * 获取匹配表达式
	 *
	 * @return 表达式
	 */
	public String getPattern() {
		return this.pattern;
	}

	/**
	 * equals
	 *
	 * @param obj 带比较对象
	 * @return 是否相等
	 */
	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof AntPathRequestMatcher other)) {
			return false;
		}
		return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod
				&& this.caseSensitive == other.caseSensitive;
	}

	/**
	 * hashCode
	 *
	 * @return hash值
	 */
	@Override
	public int hashCode() {
		int result = (this.pattern != null) ? this.pattern.hashCode() : 0;
		result = 31 * result + ((this.httpMethod != null) ? this.httpMethod.hashCode() : 0);
		result = 31 * result + (this.caseSensitive ? 1231 : 1237);
		return result;
	}

	/**
	 * toString
	 *
	 * @return 序列化字符串
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ant [pattern='").append(this.pattern).append("'");
		if (this.httpMethod != null) {
			sb.append(", ").append(this.httpMethod);
		}
		sb.append("]");
		return sb.toString();
	}

	/**
	 * 内部匹配器接口定义
	 */
	private interface Matcher {

		/**
		 * 判断路径是否与待匹配路径相匹配
		 *
		 * @param path 请求路径
		 * @return 是否与待匹配路径匹配
		 */
		boolean matches(String path);

		/**
		 * 从请求路径中获取对应的特定变量
		 *
		 * @param path 请求路径
		 * @return 获取到的变量值
		 */
		Map<String, String> extractUriTemplateVariables(String path);

	}

	private static final class SpringAntMatcher implements Matcher {

		/**
		 * 匹配器对象
		 */
		private final AntPathMatcher antMatcher;

		/**
		 * 路径表达式
		 */
		private final String pattern;

		/**
		 * 构造函数
		 *
		 * @param pattern       路径表达式
		 * @param caseSensitive 是否区分大小写
		 */
		private SpringAntMatcher(String pattern, boolean caseSensitive) {
			this.pattern = pattern;
			this.antMatcher = createMatcher(caseSensitive);
		}

		/**
		 * 路径是否匹配
		 *
		 * @param path 请求路径
		 * @return 是否匹配
		 */
		@Override
		public boolean matches(String path) {
			return this.antMatcher.match(this.pattern, path);
		}

		/**
		 * 参数值获取
		 *
		 * @param path 请求路径
		 * @return 参数值
		 */
		@Override
		public Map<String, String> extractUriTemplateVariables(String path) {
			return this.antMatcher.extractUriTemplateVariables(this.pattern, path);
		}

		/**
		 * 获取匹配器
		 *
		 * @param caseSensitive 是否区分大小写
		 * @return 匹配器队形
		 */
		private static AntPathMatcher createMatcher(boolean caseSensitive) {
			AntPathMatcher matcher = new AntPathMatcher();
			matcher.setTrimTokens(false);
			matcher.setCaseSensitive(caseSensitive);
			return matcher;
		}

	}

	/**
	 * Optimized matcher for trailing wildcards
	 */
	private static final class SubpathMatcher implements Matcher {

		private final String subpath;

		/**
		 * 路径长度
		 */
		private final int length;

		/**
		 * 是否忽略大小写
		 */
		private final boolean caseSensitive;

		private SubpathMatcher(String subpath, boolean caseSensitive) {
			Assert.isTrue(!subpath.contains("*"), "subpath 不能包含 \"*\"");
			this.subpath = caseSensitive ? subpath : subpath.toLowerCase();
			this.length = subpath.length();
			this.caseSensitive = caseSensitive;
		}

		/**
		 * 是否匹配
		 *
		 * @param path 请求路径
		 * @return 是否匹配结果
		 */
		@Override
		public boolean matches(String path) {
			if (!this.caseSensitive) {
				path = path.toLowerCase();
			}
			return path.startsWith(this.subpath) && (path.length() == this.length || path.charAt(this.length) == '/');
		}

		/**
		 * 提取不到结果
		 *
		 * @param path 请求路径
		 * @return list空对象
		 */
		@Override
		public Map<String, String> extractUriTemplateVariables(String path) {
			return Collections.emptyMap();
		}

	}

}
